package com.valsong.sandbox.mock.repository;

import com.alibaba.fastjson.TypeReference;

import com.valsong.sandbox.mock.MockConfig;
import com.valsong.sandbox.mock.exception.MockFailedException;
import com.valsong.sandbox.mock.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;


import static com.valsong.sandbox.mock.constant.MockConstants.DEFAULT_MOCK_PROFILE_PATH;
import static com.valsong.sandbox.mock.constant.MockConstants.MOCK_PROFILE_PATH_KEY;
import static com.valsong.sandbox.mock.util.ParamSupported.getParameter;


/**
 * JsonMockConfigRepository
 *
 * @author Val Song
 */
@Slf4j
public class JsonMockConfigRepository extends AbstractMockConfigRepository {

    private static final Type MOCK_CONFIG_LIST_TYPE = new TypeReference<List<MockConfig>>() {
    }.getType();

    @Override
    public void doInitMockConfigs(Map<String, String> param) {

        String mockProfilePath = getParameter(param, MOCK_PROFILE_PATH_KEY, DEFAULT_MOCK_PROFILE_PATH);

        File f = new File(mockProfilePath);

        StringBuilder builder = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new FileReader(f));

            String lineContent;

            while ((lineContent = br.readLine()) != null) {
                builder.append(lineContent);
            }

        } catch (FileNotFoundException e) {
            String errorMsg = String.format("Can't find mocker profile file! path :[%s]", mockProfilePath);
            log.error(errorMsg, e);
            throw new MockFailedException(errorMsg, e);
        } catch (IOException e) {
            String errorMsg = String.format("Read mocker profile file failed! path :[%s]", mockProfilePath);
            log.error(errorMsg, e);
            throw new MockFailedException(errorMsg, e);
        }

        String profileJson = builder.toString();

        try {
            List<MockConfig> mockConfigList = JsonUtils.parse(profileJson, MOCK_CONFIG_LIST_TYPE);
            this.MockConfigs(mockConfigList);
        } catch (Throwable e) {
            String errorMsg = String.format("Parse profile failed! path:[%s] profileJson:[%s]", mockProfilePath, profileJson);
            log.error(errorMsg, e);
            throw new MockFailedException(errorMsg, e);
        }

    }

}
